<?php

namespace XWAM\Controller;

/**
 * LogAnalysisController 类
 *
 * @since 1.0 <2015-12-1> SoChishun <14507247@qq.com> Added.
 */
class LogAnalysisController extends AppbaseController {

    function index() {
        $dir = I('dir');
        $file = I('file');
        $type = I('type', 'ALL');
        $action = I('action');
        if ('download' == $action) {
            $this->download($dir, $file);
            exit;
        }
        $m_log = new \XWAM\Model\LogAnalysisModel();
        $data = array(
            'typeset' => $m_log->get_typeset(),
            'dirs' => $m_log->get_dirs(),
            'files' => false,
            'cur_dir' => $dir,
            'cur_file' => $file,
            'cur_type' => $type,
            'cur_dir_size' => '',
            'title' => ($dir && $file) ? ($dir . '/' . $file) : '',
            'log_path' => ($dir && $file) ? (RUNTIME_PATH . 'Logs/' . $dir . '/' . $file) : '',
            'cur_type' => $type,
        );
        if ($dir) {
            $files = $m_log->get_files($dir);
            $size = 0;
            foreach ($files as $f) {
                $size+=$f['size'];
            }
            $data['cur_dir_size'] = '(' . format_bytes($size) . ')';
            $data['files'] = $files;
        }
        $this->assign('data', $data);
        $this->display();
    }

    function download($dir = '', $file = '') {
        if (!$dir || !$file) {
            exit('路径有误!');
        }
        $path = $_SERVER['DOCUMENT_ROOT'] . str_replace('/', DIRECTORY_SEPARATOR, substr(RUNTIME_PATH, 1)) . 'Logs' . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $file;
        if (!file_exists($path)) {
            exit('路径不存在!');
        }
        $filename = basename($path);
        header('Content-Type: application/octet-stream');
        header("Content-Disposition: attachment;filename=$filename");
        header('Cache-Control: max-age=0');
        readfile($path);
        exit(0);
    }

}
